import { createRouter, createWebHistory } from 'vue-router'
import Login from '../views/Login.vue'
import SuperAdmin from '../views/SuperAdmin.vue'
import NormalAdmin from '../views/NormalAdmin.vue'
import DoctorDashboard from '../views/DoctorDashboard.vue'
import DoctorRegister from '../views/DoctorRegister.vue'
import DoctorActivities from '../views/DoctorActivities.vue'
import DoctorHealthRecords from '../views/DoctorHealthRecords.vue'
import DoctorHealthStatistics from '../views/DoctorHealthStatistics.vue'
import ActivityAudit from '../views/ActivityAudit.vue'
import FeedbackManagement from '../views/FeedbackManagement.vue'

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/super-admin',
    name: 'SuperAdmin',
    component: SuperAdmin,
    meta: { requiresAuth: true, requiresSuperAdmin: true }
  },
  {
    path: '/normal-admin',
    name: 'NormalAdmin',
    component: NormalAdmin,
    meta: { requiresAuth: true, requiresSuperAdmin: false }
  },
  {
    path: '/doctor-dashboard',
    name: 'DoctorDashboard',
    component: DoctorDashboard,
    meta: { requiresAuth: true, requiresDoctor: true }
  },
  {
    path: '/doctor-register',
    name: 'DoctorRegister',
    component: DoctorRegister
  },
  {
    path: '/doctor-activities',
    name: 'DoctorActivities',
    component: DoctorActivities,
    meta: { requiresAuth: true, requiresDoctor: true }
  },
  {
    path: '/doctor-health-records',
    name: 'DoctorHealthRecords',
    component: DoctorHealthRecords,
    meta: { requiresAuth: true, requiresDoctor: true }
  },
  {
    path: '/doctor-health-statistics',
    name: 'DoctorHealthStatistics',
    component: DoctorHealthStatistics,
    meta: { requiresAuth: true, requiresDoctor: true }
  },
  {
    path: '/activity-audit',
    name: 'ActivityAudit',
    component: ActivityAudit,
    meta: { requiresAuth: true, requiresSuperAdmin: false }
  },
  {
    path: '/feedback-management',
    name: 'FeedbackManagement',
    component: FeedbackManagement,
    meta: { requiresAuth: true, requiresSuperAdmin: false }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const adminToken = localStorage.getItem('adminToken')
  const doctorToken = localStorage.getItem('doctorToken')
  const level = localStorage.getItem('level')
  
  if (to.meta.requiresAuth) {
    if (to.meta.requiresDoctor) {
      // 医生路由需要医生token
      if (!doctorToken) {
        next('/login')
        return
      }
    } else {
      // 管理员路由需要管理员token
      if (!adminToken) {
        next('/login')
        return
      }
      
      if (to.meta.requiresSuperAdmin && level !== '2') {
        next('/normal-admin')
        return
      }
    }
  }
  
  next()
})

export default router
